package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wit.witmg.entity.TOrder;
import com.wit.witmg.entity.TOrderp;
import com.wit.witmg.mapper.TOrderMapper;
import com.wit.witmg.mapper.TProdstockMapper;
import com.wit.witmg.service.ITOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.service.ITOrderpService;
import com.wit.witmg.service.ITProdstockService;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bob
 * @since 2025-02-14
 */
@Service
@RequiredArgsConstructor
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements ITOrderService {

    final ITOrderpService orderpService;
    final TProdstockMapper prodsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object add(HttpServletRequest request, String json, String prod) {
        //参数(json，prod),id为空新增(同时根据prod数组新增订单分解表)，否则为修改（同时根据prod数组修改订单分解表）;参数id删除。
//        参数stat为2时（代表签约），库存表锁库数pqt+=qt;
//        json="{\"guid\":10001,\"oid\":\"39\",\"cbn\":\"CHN_CSG_GD\",\"cna\":\"南网广东省公司\",\"ndate\":\"2025-03-15 15:29:00\",\"addr\":\"\",\"paymeth\":\"货到票到付款\",\"pr\":\"100\",\"pricetp\":\"0\",\"stat\":0,\"amount\":12200,\"date\":\"2025-02-15 15:29:14\"}";
//        prod="[{\"stat\":0,\"bn\":\"6F.1.6.D35\",\"nqt\":\"500\",\"prc\":\"8.00\",\"amount\":4000,\"remark\":\"\",\"ndate\":\"2025-03-15 15:29:00\",\"pricetp\":\"0\",\"oid\":\"39\",\"guid\":10001},{\"stat\":0,\"bn\":\"6F.1.6.D48\",\"nqt\":\"400\",\"prc\":\"20.50\",\"amount\":8200,\"remark\":\"\",\"ndate\":\"2025-03-15 15:29:00\",\"pricetp\":\"0\",\"oid\":\"39\",\"guid\":10001}]";
        TOrder t = JSONObject.parseObject(json, TOrder.class);
        if(t.getId()>0){
            if(!updateById(t)){
                return JsonResult.error(ErrorCode.ERR_504);
            }
            if(prod!=null){
                List<TOrderp> list=JSONObject.parseArray(prod,TOrderp.class);
                for(TOrderp tp:list){
                    tp.setPid(t.getId());
                }
                if(!orderpService.updateBatchById(list)){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                    return JsonResult.error(ErrorCode.ERR_504);
                }
                t.setProd(list);
            }
        }else{
            if(!save(t)){
                return JsonResult.error(ErrorCode.ERR_504);
            }
            if(prod!=null){
                List<TOrderp> list=JSONObject.parseArray(prod,TOrderp.class);
                for(TOrderp tp:list){
                    tp.setPid(t.getId());
                }
                if(!orderpService.saveBatch(list)){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                    return JsonResult.error(ErrorCode.ERR_504);
                }
                t.setProd(list);
            }
        }
        if(t.getStat()==2){//库存表(TProdstock)锁库数pqt+=qt;
            for (TOrderp tdp : t.getProd()) {
                prodsMapper.updatePqt(tdp.getBn(),tdp.getNqt());
            }
        }
        return JsonResult.success(t);
    }

    @Override
    public Object get(HttpServletRequest request, Integer id, String cbn, String oid,String stat) {
        //参数：cid客户id返回cid对应的数据、oid返回oid以参数开头并包含参数的数据；id返回单条数据，常用于连表查询。
        QueryWrapper<TOrder> qw=new QueryWrapper<>();
        if(id!=null){
            TOrder t=getById(id);
            if(t==null){
                return JsonResult.error(ErrorCode.ERR_313);
            }
            t.setProd(orderpService.list(new QueryWrapper<TOrderp>().eq("pid",id)));
            return JsonResult.success(t);
        }else if(cbn!=null){
            qw.like("cbn",cbn);
            List<TOrder> list=list(qw);
            setProdForOrders(list);
            return JsonResult.success(list);
        }else if(oid!=null){
            qw.like("oid",oid);
            List<TOrder> list=list(qw);
            setProdForOrders(list);
            return JsonResult.success(list);
        }else if(stat!=null){
            if(stat.contains(",")){
                String[] ss=stat.split(",");
                for (int i = 0; i < ss.length; i++) {
                    if (i == 0) {
                        qw.eq("stat", ss[i]);
                    } else {
                        qw.or().eq("stat", ss[i]);
                    }
                }
            }else{
                qw.eq("stat",stat);
            }
            List<TOrder> list=list(qw);
            setProdForOrders(list);
            return JsonResult.success(list);
        }

        return JsonResult.error(ErrorCode.ERR_200);
    }

    private void setProdForOrders(List<TOrder> orders) {
        for (TOrder t : orders) {
            t.setProd(orderpService.list(new QueryWrapper<TOrderp>().eq("pid", t.getId())));
        }
    }

    @Override
    public Object del(HttpServletRequest request, Integer id) {
        return null;
    }
}
